//
//  CNConsigneeAddressTableViewController.m
//  BeeQuick_19
//
//  Created by 赵玉忠 on 16/9/25.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNConsigneeAddressTableViewController.h"
#import "CNConsigneeAddressTableViewCell.h"
#import "CNConsigneeModel.h"
#import "CNAddNewAddressViewController.h"
#import "CNCNSelfAddressTableViewCell.h"
#import "CNOtherAddressTableViewCell.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface CNConsigneeAddressTableViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;
@property (nonatomic,assign) CGFloat jingdu;
@property (nonatomic,assign) CGFloat weidu;

@property (nonatomic,weak) UIButton *leftButton;
@property (nonatomic,weak) UIButton *rightButton;
@property (nonatomic,weak) UILabel *leftLabel;
@property (nonatomic,weak) UILabel *rightLabel;
@property (nonatomic,assign) BOOL leftTag;

@property (nonatomic,strong) NSMutableArray *modelArray;
@property (nonatomic,weak) UIView *bottomButtonView;
@end
static NSString *CNConsigneeAddressTableViewCellID = @"CNConsigneeAddressTableViewCellID";
static NSString *CNCNSelfAddressTableViewCellID = @"CNCNSelfAddressTableViewCellID";
static NSString *CNOtherAddressTableViewCellID = @"CNOtherAddressTableViewCellID";
@implementation CNConsigneeAddressTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    self.view.backgroundColor = [UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1];
    
    //添加底部按钮
//    [self addBottomButton];
    
//    self.tableView.rowHeight = 80;
    
    //加载数据
    [self loadData];

    
    //自定义导航条
    [self loadNavBar];
    
    //注册cell
    [self loadNibCell];
    
    //隐藏多余cell
    [self setExtraCellLineHidden:self.tableView];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CNCNSelfAddressTableViewCell" bundle:nil] forCellReuseIdentifier:CNCNSelfAddressTableViewCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"CNOtherAddressTableViewCell" bundle:nil] forCellReuseIdentifier:CNOtherAddressTableViewCellID];

}

#pragma mark - 加载cell
-(void)loadNibCell{
    [self.tableView registerNib:[UINib nibWithNibName:@"CNConsigneeAddressTableViewCell" bundle:nil] forCellReuseIdentifier:CNConsigneeAddressTableViewCellID];
}

#pragma mark - loadNavBar
-(void)loadNavBar{
    //titleView
    
    NSArray *segmentedArray = [[NSArray alloc]initWithObjects:@"收货地址",@"店铺自取",nil];
    //初始化UISegmentedControl
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc]initWithItems:segmentedArray];
//    segmentedControl.tintColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    segmentedControl.tintColor = [UIColor whiteColor];
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor darkGrayColor],NSForegroundColorAttributeName,nil];
    [segmentedControl setTitleTextAttributes:dic forState:UIControlStateSelected];
    NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor],NSForegroundColorAttributeName,nil];
    [segmentedControl setTitleTextAttributes:dic1 forState:UIControlStateNormal];
    
    [segmentedControl setWidth:90.0 forSegmentAtIndex:0];
    [segmentedControl setWidth:90.0 forSegmentAtIndex:1];
    [segmentedControl addTarget:self action:@selector(changeView:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = segmentedControl;

    
    //加载nib Cell
//    [self loadNibCell];
    
    [self leftButtonClick];
    segmentedControl.selectedSegmentIndex = 0;
    

}

-(void)changeView:(UISegmentedControl *)seg{
    NSInteger index = seg.selectedSegmentIndex;
    if (index == 0) {
        [self leftButtonClick];
    }else{
        [self rightButtonClick];
    }
}

#pragma 左边按钮的点击
-(void)leftButtonClick{
    self.leftTag = YES;
    self.leftButton.selected = YES;
    self.rightButton.selected = NO;
    [self.tableView reloadData];
}
#pragma 右边按钮的点击
-(void)rightButtonClick{
    self.leftTag = NO;
    self.rightButton.selected = YES;
    self.leftButton.selected = NO;
    
//    [SVProgressHUD show];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [SVProgressHUD dismiss];
//        [self.tableView reloadData];
//    });
    
//    [self.tableView reloadData];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 处理耗时操作的代码块...
        [self _startLocation];
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
                [self.tableView reloadData];
                [self labelAnimation];
        });
        
    });
    
//    [self labelAnimation];
    
}
#pragma mark - 弹出经纬度动画
-(void)labelAnimation{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, -50, width, 50)];
    label.backgroundColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    label.text = [NSString stringWithFormat:@" 经度：116.000000  纬度 ：39.000000"];
    [self.view addSubview:label];
    [UIView animateWithDuration:1.5 animations:^{
        CGRect frame = label.frame;
        frame.origin.y = 0;
        label.frame = frame;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:1.5 animations:^{
            CGRect frame = label.frame;
            frame.origin.y = -50;
            label.frame = frame;
        }];
    }];
}
#pragma mark -返回按钮的点击
-(void)backButtonClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.leftTag == 1) {
        return 1;
    }else{
        return 2;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.leftTag == 1) {
        return self.modelArray.count;
    }else{
        if (section == 0) {
            return 1;
        }else{
            return 3;
        }
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTag == 1) {
        CNConsigneeAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNConsigneeAddressTableViewCellID forIndexPath:indexPath];
        cell.model = self.modelArray[indexPath.row];
        
        
        [cell addTagAndButtonClickTarget:self andWithTag:indexPath.row andAction:@selector(pushToAddAddressVC:)];
        return cell;
    }else{
        if (indexPath.section == 0) {
            CNCNSelfAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNCNSelfAddressTableViewCellID forIndexPath:indexPath];
            return cell;
        }else{
            CNOtherAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CNOtherAddressTableViewCellID forIndexPath:indexPath];
            return cell;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.leftTag == 1) {
        return 80;
    }else{
        if (indexPath.section == 0) {
            return 50;
        }else{
            return 110;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.leftTag == 1) {
        return 0;
    }else{
        return 20;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.leftTag == 1 && section == 0) {
        return 0;
    }else if (self.leftTag == 0  && section == 1){
        return 0;
    }else{
        return 20;
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.leftTag == 0) {
        if (section == 1) {
            return @"附近的自提点";
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}



#pragma mark - 从网络获取数据
-(void)loadDataFromNetWork{
    [SVProgressHUD show];
    // 1. url
    NSURL *url = [NSURL URLWithString:@"http://iosapi.itcast.cn/loveBeen/MyAdress.json.php"];
    // 2. 请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 2.1 更改请求方式.一般都使用大写.
    request.HTTPMethod = @"POST";
    
    //    [request setValue:@"text/html" forHTTPHeaderField:@"content-type"];
    
    // 2.2 设置请求体
    NSData *data = [NSJSONSerialization dataWithJSONObject:@{@"call":@"12"} options:0 error:NULL];
    //    NSString *bodyString = [NSString stringWithFormat:@"{\"cell\":\"12\"}"];
    request.HTTPBody = data;
    // 3. 发送请求
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSLog(@"%@", [NSThread currentThread]);
        
        
        // 4. 错误判断
        if (error != nil || data.length == 0) {
            NSLog(@"%@", error);
            return;
        }
        
        // 5. 数据反序列化
        id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        NSLog(@"%@",result);
        //转成模型
        NSArray *array = [NSArray yy_modelArrayWithClass:[CNConsigneeModel class] json:result[@"data"]];
        self.modelArray = [NSMutableArray arrayWithArray:array];
        
        CNConsigneeModel *model = self.modelArray[0];
        NSLog(@"%@",model.gender);

        //归档
        // temp路径
        NSString* tempPath = NSTemporaryDirectory();
        
        // file路径
        NSString* filePath = [tempPath stringByAppendingPathComponent:@"shopCar.address"];
        
        // 归档
        [NSKeyedArchiver archiveRootObject:self.modelArray toFile:filePath];
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
        
    }] resume];

}
#pragma mark - 加载数据
-(void)loadData{
    
    //从本地获取数据、解档
    // temp路径
    NSString* tempPath = NSTemporaryDirectory();
    // file路径
    NSString* filePath = [tempPath stringByAppendingPathComponent:@"shopCar.address"];
    NSLog(@"%@",filePath);
    // 解档
    self.modelArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

    if (self.modelArray == nil) {
        //从网络获取数据
        [self loadDataFromNetWork];
    }
    
}

#pragma mark - 隐藏多余cell

-(void)setExtraCellLineHidden: (UITableView *)tableView
{
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
}

#pragma mark - 添加底部按钮
-(void)addBottomButton{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *buttomView = [UIView new];
    self.bottomButtonView = buttomView;
    buttomView.backgroundColor = [UIColor whiteColor];
    [window addSubview:buttomView];
    [buttomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(window);
        make.height.offset(60);
    }];
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [addButton setTitleEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    [addButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    addButton.layer.cornerRadius = 5;
    addButton.backgroundColor = [UIColor colorWithRed:252/255.0 green:211/255.0 blue:52/255.0 alpha:1];
    [addButton setTitle:@"+新增地址" forState:UIControlStateNormal];
    addButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [buttomView addSubview:addButton];
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttomView).offset(50);
        make.centerY.equalTo(buttomView);
        make.right.equalTo(buttomView).offset(-50);
        make.height.offset(40);
    }];
}

#pragma mark - addButtonClick 跳转到新增地址页面（同样也是编辑页面）
-(void)addButtonClick{
    CNAddNewAddressViewController *newAddressCV = [CNAddNewAddressViewController new];
    [self.navigationController pushViewController:newAddressCV animated:YES];
    newAddressCV.tag = 0;
    newAddressCV.consigneeAddressModelArray = self.modelArray;
}

#pragma marl - 移除窗口视图
-(void)viewWillDisappear:(BOOL)animated{
    [self.bottomButtonView removeFromSuperview];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self addBottomButton];
    
    CNConsigneeModel *model = self.modelArray[0];
    NSLog(@"%@",model.gender);
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
    [self.tableView reloadData];
}

#pragma mark - 侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.modelArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
        // temp路径
        NSString* tempPath = NSTemporaryDirectory();
        
        // file路径
        NSString* filePath = [tempPath stringByAppendingPathComponent:@"shopCar.address"];
        
        // 归档
        [NSKeyedArchiver archiveRootObject:self.modelArray toFile:filePath];

        
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}
#pragma mark - 编辑按钮的点击
-(void)pushToAddAddressVC:(UIButton *)sender{
    CNAddNewAddressViewController *newAddressCV = [CNAddNewAddressViewController new];
    [self.navigationController pushViewController:newAddressCV animated:YES];
    newAddressCV.tag = 1;
    newAddressCV.consigneeAddressModelArray = self.modelArray;
    newAddressCV.modelIndex = sender.tag;
}

#pragma mark - 获取当前位置信息
-(void)_startLocation{
    CLLocationManager *locationManager = [[CLLocationManager alloc]init];
    self.locationManager = locationManager;
    self.locationManager.delegate = self;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        [_locationManager requestWhenInUseAuthorization];
    }
    
    //设置定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    self.locationManager.distanceFilter = 10.0f;
    
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        NSLog(@"requestAlwaysAuthorization");
        [self.locationManager requestAlwaysAuthorization];
    }
    
    
    [self.locationManager startUpdatingLocation];
}

#pragma mark -CLLocationManager 代理方法
-(void)locationManager:(nonnull CLLocationManager *)manager didUpdateLocations:(nonnull NSArray<CLLocation *> *)locations{
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oCoordinate = newLocation.coordinate;
    NSLog(@"旧的经度 %f 旧的维度 %f",oCoordinate.longitude,oCoordinate.latitude);
    
    
    
    self.jingdu = oCoordinate.longitude;
    self.weidu = oCoordinate.latitude;
    
    
    
    
    //    self.longitute = [NSNumber numberWithDouble:coordinate.longitude];
    //    self.latitude = [NSNumber numberWithDouble:coordinate.latitude];
    
    [self.locationManager stopUpdatingLocation];
    
    //创建地理位置解码器对象
    CLGeocoder *geoCorder = [[CLGeocoder alloc]init];
    [geoCorder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
            NSDictionary *location = [place addressDictionary];
            NSLog(@"国家：%@",location[@"Country"]);
            NSLog(@"城市：%@",location[@"State"]);
            NSLog(@"区：%@",location[@"Sublocality"]);
            
            NSLog(@"位置：%@",place.name);
            NSLog(@"国家：%@",place.country);
            NSLog(@"城市：%@",place.locality);
            NSLog(@"区：%@",place.subLocality);
            NSLog(@"街道：%@",place.thoroughfare);
            NSLog(@"子街道：%@",place.subThoroughfare);
        }
    }];
    
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
}

@end
